﻿using Caliburn.Micro;
using GYMm.UI.ViewModels;
using GYMm.UI.Views;
using LocalSettings;
using Storage.Repositories.Base;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using System.Threading.Tasks;
using Windows.ApplicationModel;
using Windows.ApplicationModel.Activation;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Media.Animation;
using Windows.UI.Xaml.Navigation;

// The Blank Application template is documented at http://go.microsoft.com/fwlink/?LinkId=391641

namespace GYMm
{
    /// <summary>
    /// Provides application-specific behavior to supplement the default Application class.
    /// </summary>
	public sealed partial class App
	{
		private WinRTContainer _container;
		
		public App()
		{
			InitializeComponent();
			this.UnhandledException += App_UnhandledException;
		}

		void App_UnhandledException(object sender, UnhandledExceptionEventArgs e)
		{
			LocalSettings.GYMSettingsStorage.LastErrorStackTrace += e.Exception.StackTrace;
		}

		protected override void Configure()
		{
			_container = new WinRTContainer();
			_container.RegisterWinRTServices();

            var repStorage = new RepStorage();
            _container.RegisterInstance(typeof(RepStorage), "RepStorage", repStorage);

            var t = repStorage.CreateTables();

			ConfigureModels();
			ConfigureViewModels();			
		}

		private void ConfigureModels()
		{
			_container.Singleton<Models.GymModel>();
		}

		private void ConfigureViewModels()
		{
			_container.PerRequest<DashboardViewModel>();
			_container.PerRequest<ExerciseViewModel>();
			_container.PerRequest<StartViewModel>();
		}

		protected override object GetInstance(Type service, string key)
		{
			var instance = _container.GetInstance(service, key);
			if (instance != null)
				return instance;
			throw new Exception("Could not locate any instances.");
		}

		protected override IEnumerable<object> GetAllInstances(Type service)
		{
			return _container.GetAllInstances(service);
		}

		protected override void BuildUp(object instance)
		{
			_container.BuildUp(instance);
		}

		protected override void PrepareViewFirst(Frame rootFrame)
		{
			_container.RegisterNavigationService(rootFrame);
		}

		protected override void OnLaunched(LaunchActivatedEventArgs args)
		{
            DisplayRootView<DashboardView>();
		}
	}
}